
using UnityEngine;
using System.Collections;
public class Group
{
	public Vector3 target;
	public ArrayList myUnits = new ArrayList();

	public bool updateGroup(){
		if(myUnits.Count==0)
			return false;
		int num = (int)Mathf.Sqrt(myUnits.Count);
		float spacing=3-Mathf.Min((float)num/10,2.5f);
		Vector3 origin = target;
		origin.x-=num/2*spacing;
		origin.z-=num/2*spacing;
		ArrayList targs = new ArrayList();
		for(int i=0;i<myUnits.Count;){
			Unit u = (Unit)myUnits[i];
			if(u.myGroup!=this){
				myUnits.RemoveAt(i);
				continue;
			}
			if(u.currentTarget!=null && !u.currentTarget.isDead() && !targs.Contains(u.currentTarget)){
				if((u.currentTarget.obj.transform.position-target).magnitude<u.attackRange)
					targs.Add(u.currentTarget);
			}
			i++;
		}
		for(int i=0;i<myUnits.Count;){
			Vector3 loc = origin;
			int x=i/num,y=i%num;
			loc.x+=x*spacing;
			loc.z+=y*spacing;
			Unit u = (Unit)myUnits[i];

			if(u.currentTarget==null && targs.Count>0){
				u.awake();
				u.target(((Unit)targs[(int)(targs.Count*Random.value)]).obj.transform.position);
			}
			else{
				u.target(loc);
			}
			//if((u.obj.transform.position-loc).magnitude<1)
			//	u.relax();
			//else
			i++;
		}
		return true;
	}

}